package com.atguigu.spring.tx.xml.service.impl;

import com.atguigu.spring.tx.xml.dao.BookDao;
import com.atguigu.spring.tx.xml.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author wk
 * @create 2021-06-03 18:15
 */
@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookDao userDao;

    @Override
    // 通过这个注解和属性设置使用被调用者的事务
    @Transactional(
            propagation = Propagation.REQUIRES_NEW,
            // 四种MySQL数据的隔离级别 和MySQL默认的隔离级别
            // 可重复读，mysql默认的隔离级别，避免了幻读的情况
            isolation= Isolation.DEFAULT,
            rollbackFor = {ArithmeticException.class},
            // timeout默认-1一直等待 单位默认为秒
            timeout = 3
    )
    public void buyBook(int userId, int bookId) {
        // 根据图书id查询图书价格
      Double price=  userDao.getPriceByBookId(bookId);
        // 更新图书库存
        userDao.updateStock(bookId);
        // 更新账户余额
        userDao.UpdateBalance(userId,price);
        //System.out.println(3/0);
    }
}
